// 机构员工(医生)
// 导入数据库查询方法
const { getOne, update, query } = require('../../utils/dbTools');
const { isValidator3 } = require('../../utils/util');
const { getUploadedUrl } = require('../../utils/upload');

const { getBusinessInfo, addBusinessInfo } = require('../../model/business')
const { updateMember } = require('../../model/member')

const tableName = 'member';
const businessTableName = 'business';


// 查询当前医生列表
const doctorList = async (req, res) => {
    const output = {
        code: 200,
        msg: "操作成功"
    }
    const { bus_id, page, size } = req.query;
    var sql = `select s.*,b.title as bus_title from ${tableName} s inner join ${businessTableName} b on s.bus_id=b.id`;
    // 机构id
    if (bus_id) {
        sql += ` where bus_id=${bus_id}`;
    }
    if (page && size) {
        sql += ` limit ${(page - 1) * size},${size}`;
    }
    const result = await query(sql);
    if (!result) {
        output.code = 500;
        output.msg = "操作失败";
        return res.send(output);
    }
    result.forEach(async (item) => {
        if (item.tags) {
            item.tags = item.tags.split(',');
        }
    });
    output.data = result;
    res.send(output);
}

// 查询医生的详情
const doctorDetail = async (req, res) => {
    const output = {
        code: 200,
        msg: "操作成功"
    }
    const { id } = req.query;
    if (!id) {
        output.code = 500;
        output.msg = '参数错误:缺少id';
        return res.send(output);
    }
    const result = await getOne(tableName, { id });

    if (!result) {
        output.code = 500;
        output.msg = '未查询到结果';
        return res.send(output);
    }
    // 查询企业信息
    if (result.bus_id) {
        const { title } = await getBusinessInfo({ id: result.bus_id });
        result.bus_title = title;
    }

    if (result.tags) {
        result.tags = result.tags.split(',');
    }
    // 返回结果
    output.data = {
        ...result
    }
    delete output.data.password;
    res.send(output);

}

// 更新信息
const doctorUpdate = async (req, res) => {
    const output = {
        code: 200,
        msg: "操作成功"
    }
    const { id, phone } = req.body;
    if (!id) {
        output.code = 500;
        output.msg = "参数错误:缺少id"
        return res.send(output);
    }
    // 如果提交了手机号码
    if (phone) {
        // 检查手机号码是否重复
        if (!await isValidator3(`select * from ${tableName} where phone='${phone}' and id<>${id} limit 1`)) {
            output.code = 500;
            output.msg = "手机号码已存在"
            return res.send(output);
        }
    }
    // 要更新的信息
    const payload = { ...req.body }
    // 获取上传完成的图片地址
    const { file } = req;
    if (file) {
        payload.avatar = getUploadedUrl(file);
    }
    delete payload.id
    await update(id, payload, tableName,);
    res.send(output);
}


/**
 * 退出当前所在企业
 * 
 * */
const accountExit = async (req, res) => {
    const output = {
        code: 200, msg: '操作成功'
    }
    // 获取登录账号id
    const { id } = req.loginInfo
    // 如果是企业账号超级管理员, 则不允许退出该企业
    const result = await getBusinessInfo({ member_id: id })

    if (result) {
        output.code = 500
        output.msg = '系统错误:企业超级管理员账号,不允许退出该企业,请先转让超级管理员身份'
        return res.send(output)
    }
    // 账号类型重置为普通账号
    const result2 = await updateMember(id, { account_type: 1, bus_id: 0 })
    output.data = {
        changedRows: result2?.changedRows
    }
    res.send(output)
}

/**
 * 账号升级: 普通账号升级为企业账号
 * 
 * */

const accountUpgrade = async (req, res) => {
    const output = {
        code: 200, msg: '操作成功'
    }
    // 企业名称, 联系电话, 省市区
    const { title, phone, province, city, county } = req.body
    // 在business数据表中新增一条记录, 状态为未认证企业
    if (await getBusinessInfo({ title })) {
        output.code = 500
        output.msg = "操作失败: 企业名称已存在,请确认"
        return res.send(output)
    }
    const { id: member_id } = req.loginInfo
    // 记录企业信息
    const insertId = await addBusinessInfo(member_id, title, phone, province, city, county)
    if (!insertId) {
        output.code = 500
        output.msg = "操作失败: 写入企业信息失败"
        return res.send(output)
    }
    // 更新账号类型: 更新为企业信息
    await updateMember(member_id, { account_type: 3, bus_id: insertId })
    output.data = { insertId }
    res.send(output)
}



module.exports = {
    doctorList,
    doctorDetail,
    doctorUpdate,
    accountExit,
    accountUpgrade
}